package org.phpj.examples;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.phpj.parser.Parser;
import org.phpj.parser.ParserException;

public class Httpd {
	private Server server;

	public Server getServer() {
		return server;
	}
	

	public static void main(String[] args) throws Exception {
		new Httpd().startServer();
	}
	
	public void startServer() {
		server = new Server(8080);
		
		server.setHandler(createHandler());
		
		try {
			server.start();
			java.lang.System.out.println("Started server on port 8080");

					
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	private Handler createHandler() {
		return new AbstractHandler() {
			
			@Override
			public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		
				Map<String, Object> data = new HashMap<String, Object>();	
		
				File targetFile = new File(target);

				if(targetFile.isFile())
					targetFile = new File(".");
					
				
				System.out.println("Target: " + target);

				if(targetFile.isDirectory()) {
					data.put("dir", targetFile);
					data.put("files", targetFile.listFiles());
				} else if(targetFile.isFile()) {
					byte[] encoded = Files.readAllBytes(Paths.get(target));
					data.put("fileOutput", Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString());
					data.put("fileName", target);
				} else {
					response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				}

				System.out.println("Data: " + data);
				
				Parser parser = new Parser(new File("examples/dir.phpj"));

				try {
					OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
					parser.parse(data, writer);
					writer.close();
				} catch (Exception e) {
					e.printStackTrace();
					ParserException p = new ParserException(parser.getLine(), "Could not parse file");
					p.initCause(e);
					p.printStackTrace(new PrintStream(response.getOutputStream()));
				} 
				
				baseRequest.setHandled(true);
			}
		};
	}
}
